<?php
(defined('SYSTEM_ACT') or defined('LOCK_TO_INSTALL')) or exit('Access Denied');
define('WEB_ROOT', str_replace("\\",'/', dirname(dirname(__FILE__))));
if(is_file(WEB_ROOT.'/config/version.php'))
{
	require WEB_ROOT.'/config/version.php';
}
if(is_file(WEB_ROOT.'/config/debug.php'))
{
	require WEB_ROOT.'/config/debug.php';
}
define('SAPP_NAME', 'baijiacms');
define('SAPP_VERSION', '4.1.4');
define('CORE_VERSION', 20170105);
header('Content-type: text/html; charset=UTF-8');
define('SYSTEM_WEBROOT', WEB_ROOT);
define('TIMESTAMP', time());
define('SYSTEM_IN', true);
defined('DATA_PROTECT') or define('DATA_PROTECT', false);
defined('CUSTOM_VERSION') or define('CUSTOM_VERSION', false);
date_default_timezone_set('PRC');
$document_root = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));
$document_root =str_replace("//","/",$document_root);
if(empty($document_root)||substr($document_root, -1)!='/')
{
		$document_root=$document_root. '/';
}
define('WEBSITE_FOOTER', $document_root);	
define('SESSION_PREFIX', $_SERVER['HTTP_HOST']);	
define('WEB_WEBSITE', $_SERVER['HTTP_HOST']);	
define('WEBSITE_ROOT', 'http://'.$_SERVER['HTTP_HOST'].$document_root);
define('LOCAL_ATTACHMENT_WEBROOT', WEBSITE_ROOT.'attachment/');
define('RESOURCE_ROOT', WEBSITE_ROOT.'assets/');

define('SYSTEM_ROOT', WEB_ROOT.'/system/');	
define('CUSTOM_ROOT', WEB_ROOT.'/custom/');	
define('ADDONS_ROOT', WEB_ROOT.'/addons/');
defined('DEVELOPMENT') or define('DEVELOPMENT',0);
defined('SQL_DEBUG') or define('SQL_DEBUG', 0);
define('REGULAR_EMAIL', '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/i');
define('REGULAR_MOBILE', '/1\d{10}/');
define('REGULAR_USERNAME', '/^[\x{4e00}-\x{9fa5}a-z\d_\.]{3,15}$/iu');
define('WEIXIN_ROOT', 'https://mp.weixin.qq.com');
define('MAGIC_QUOTES_GPC', (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) || @ini_get('magic_quotes_sybase'));
define('MOBILE_SESSION_ACCOUNT', SESSION_PREFIX."mobile_sessionAccount");
define('MOBILE_ACCOUNT', SESSION_PREFIX."mobile_account");
define('MOBILE_WEIXIN_OPENID', SESSION_PREFIX."mobile_weixin_openid");
define('WEB_SESSION_ACCOUNT', SESSION_PREFIX."web_account");

if(!session_id())
{
session_start();
header("Cache-control:private");
}
if(DEVELOPMENT) {
	ini_set('display_errors','1');
error_reporting(E_ALL ^ E_NOTICE);
	//error_reporting(E_ERROR  | E_PARSE);
} else {
	error_reporting(0);
}
ob_start();
if(MAGIC_QUOTES_GPC) {
	  function stripslashes_deep($value){ 
         $value=is_array($value)?array_map('stripslashes_deep',$value):stripslashes($value); 
         return $value; 
     } 
     $_POST=array_map('stripslashes_deep',$_POST); 
     $_GET=array_map('stripslashes_deep',$_GET); 
     $_COOKIE=array_map('stripslashes_deep',$_COOKIE); 
     $_REQUEST=array_map('stripslashes_deep',$_REQUEST); 
}
$_GP = $_CMS =  array();
$_GP = array_merge($_GET, $_POST, $_GP);
function irequestsplite($var) {
	if (is_array($var)) {
		foreach ($var as $key => $value) {
			$var[htmlspecialchars($key)] = irequestsplite($value);
		}
	} else {
		$var = str_replace('&amp;', '&', htmlspecialchars($var, ENT_QUOTES));
	}
	return $var;
}
function prr($data){
    echo '<pre>';
    print_r($data);
}
function add_udid(){
	$where = 'is_udid=0 and isagent=1 and status=1';
    $sql = 'select id from ' . tablename('eshop_member') . ' where '.$where;
    $member_list = pdo_fetchall($sql);
    foreach ((array)$member_list as $k => $v) {
        $number01 = 'FT' . random(6);
        $number02 = 'FT' . random(6);
        $data['fx_id'] = $v['id'];
        $data['udid'] = $number01;
        pdo_insert('eshop_member_udid', $data);
        $data['udid'] = $number02;
        pdo_insert('eshop_member_udid', $data);
        pdo_query('update ' . tablename('eshop_member') . ' set is_udid=1 where id=:id ', array(':id' => $v['id']));
    }
}
function agent_num($id){
    $info = pdo_fetch("select id,agentsuccessid,agentnum from " . tablename("eshop_member") . " where id='".$id."'");
    if($info['id']) {
        mysqld_update('eshop_member', array('agentnum' =>$info['agentnum']+1), array('id' => $info['id']));
        if ($info['agentsuccessid']) {
            agent_num($info['agentsuccessid']);
        }
    }
}
function agent_arr(){
   $arr = array(
        '10'=>array(98,100),
        '30'=>array(198,200),
        '60'=>array(360,400),
        '90'=>array(580,800),
        '120'=>array(690,1600),
        '200'=>array(880,3200),
        '580'=>array(1280,6800),
        '800'=>array(1580,16000),
        '1600'=>array(1880,20000),
        '3200'=>array(2680,38000),
        '5000'=>array(2880,60000),
        '8000'=>array(3980,80000),
        '20000'=>array(5980,120000),
        '60000'=>array(12800,180000),
        '100000'=>array(13800,320000),
        '300000'=>array(68000,600000),
        '600000'=>array(88888,1000000),
        '800000'=>array(288888,3000000)
    );
    return $arr;
}
function agent_success(){
    $arr = agent_arr();
    if (is_use_weixin()) {
        $openid = get_sysopenid(true);
    } else {
        $openid = get_sysopenid(false);
    }
    $memberinfo = get_member_info($openid);
    foreach ((array)$arr as $kk => $vv) {
        $sql = "select id,openid,agentallid,agenttime,agentprice from " . tablename('eshop_member') . " where agentnum>=" . $kk." and openid='".$memberinfo['openid']."'";
        $list = pdo_fetch($sql);
        if ($list['id']) {
            $is_give = pdo_fetchcolumn("select count(*) from " . tablename('eshop_member_success') . " where user_id=".$list['id']." and price=".$vv[1]);
            if(!$is_give) {
                $id_arr = explode(',',$list['agentallid']);
                $sql = "select agenttime from " . tablename('eshop_member') . " where id =".$id_arr[$kk-1];
                $time = pdo_fetchcolumn($sql);
                $sql = "select price from " . tablename("eshop_order") . " where paytime>" . $time . " and openid='" . $list['openid'] . "' order by price desc";
                $check_price = pdo_fetchcolumn($sql);

                if ($check_price >= $vv[0]) {
                    $data['user_id'] = $list['id'];
                    $data['price'] = $vv[1];
                    $data['number'] = $kk;
                    $data['buy_price'] = $vv[0];
                    $data['add_time'] = time();
                    $result = pdo_insert('eshop_member_success', $data);
                    if ($result) {
                        mysqld_update('eshop_member', array('agentprice' => $vv[1]), array('id' => $list['id']));
                        member_gold($list['openid'], $vv[1], 'addgold', '分销达到条件赠送金额');
                        $set = globalSetting('shop');
                        $logno = m('common')->createNO('member_log', 'logno', 'RC');
                        $datas = array(
                            'openid' => $list['openid'],
                            'logno' => $logno,
                            'uniacid' => 1,
                            'type' => '0',
                            'createtime' => TIMESTAMP,
                            'status' => '1',
                            'title' => '分销达到条件赠送金额',
                            'money' => $vv[1],
                            'rechargetype' => 'system'
                        );
                        pdo_insert('eshop_member_log', $datas);
                    }
                }
            }
        }
    }
}

function get_agent_number($user_id){
	$sql = "select id,fx_id,udid,user_id from " . tablename('eshop_member_udid') . " where status=1 and fx_id='".$user_id."'";
	$list = pdo_fetchall($sql);
	foreach((array)$list as $k=>$v){
		$_SESSION['agentnumber'][$v['id']] = $v;
		if(!$v['user_id']){
			continue;
		}
		get_agent_number($v['user_id']);
	}
}

function agent_success_number($number,$price,$agentallid){
    $sql = "select openid,agenttime from " . tablename('eshop_member') . " where id in(" . $agentallid . ")";
	$all_list = pdo_fetchall($sql);
	$time = $all_list[$number-1]['agenttime'];
	$number = 0;
	foreach ((array)$all_list as $kkkk => $vvvv) {
		$sql = "select price from " . tablename("eshop_order") . " where paytime>" . $vvvv['agenttime'] . " and paytime>" . $time . " and openid='" . $vvvv['openid'] . "' order by price desc";
		$coupon_count = pdo_fetchcolumn($sql);
		if ($coupon_count >= $price) {
			$number += 1;
		}
	}
	return $number;
}
function agent_id($id,$agentid){
    if($agentid>0) {
        $info = pdo_fetch("select id,agentsuccessid,agentallid from " . tablename("eshop_member") . " where id='" . $agentid . "'");
        if ($info['id']) {
            if ($info['agentallid']) {
                $str = $info['agentallid'] . ',' . $id;
            } else {
                $str = $id;
            }
            $result = mysqld_update('eshop_member', array('agentallid' => $str), array('id' => $info['id']));
            if($result){
                agent_id($id, $info['agentsuccessid']);
            }
        }
    }
}
function get_agent_list($id,$data){
	$sql = "select id,nickname,agentsuccessid,agentnum,mobile,agentgrade from " . tablename('eshop_member') . " where agentsuccessid=$id";
	$all_list = pdo_fetchall($sql);
	foreach((array)$all_list as $k=>$v){
		$_SESSION['agentlist'][$v['id']] = $v;
		if(!$v['agentnum']){
			continue;
		}
		get_agent_list($v['id'],$data);
	}
}

function get_agent_lists($id,$data){
    $sql = "select id,nickname,agentsuccessid,agentnum,mobile,agentgrade from " . tablename('eshop_member') . " where agentsuccessid=$id";
    $all_list = pdo_fetchall($sql);
    if(count($all_list)){
        $_SESSION['agentlist']['content'] = $_SESSION['agentlist']['content'].'<ul style="display:none;">';
    }
    foreach((array)$all_list as $k=>$v){
        $_SESSION['agentlist']['content'] = $_SESSION['agentlist']['content'].'<li><span class="folder">'.$v['nickname'].'('.$v['mobile'].')</span>';
        if(!$v['agentnum']){
            continue;
        }
        get_agent_lists($v['id'],$data);
        $_SESSION['agentlist']['content'] = $_SESSION['agentlist']['content'].'</li>';
    }
    if(count($all_list)){
        $_SESSION['agentlist']['content'] = $_SESSION['agentlist']['content'].'</ul>';
    }
    return $_SESSION['agentlist']['content'];
}

function GetOpenid(){
    if ($_SESSION['openid']){
        return array('openid'=>$_SESSION['openid']);
    }
    if (!isset($_GET['code'])) {
        $baseUrl = urlencode(get_url());
        $url = __CreateOauthUrlForCode($baseUrl);
        Header("Location: $url");
        exit();
    } else {
        // 上面跳转, 这里跳了回来
        //获取code码，以获取openid
        $code = $_GET['code'];
        $data = GetOpenidFromMp($code);
        $access_token2 = getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token2&openid=".$data['openid'];
        $subscribe_info = httpRequest($url, 'GET');
        return $subscribe_info;
    }
}
function getAccessToken() {
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa5c5ce908eaa26b9&secret=2d409fb461f63d0103c783ab5f54a49d";
    $return = httpRequest($url, 'GET');

    $return = json_decode($return, 1);
    return $return['access_token'];
}

function get_url() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;

}
function GetOpenidFromMp($code) {
    //通过code换取网页授权access_token  和 openid
    $url = __CreateOauthUrlForOpenid($code);
    $ch = curl_init(); //初始化curl
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置超时
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $res = curl_exec($ch); //运行curl，结果以jason形式返回
    $data = json_decode($res, true); //取出openid access_token
    curl_close($ch);
    return $data;
}
function __CreateOauthUrlForCode($redirectUrl) {
    $urlObj["appid"] = 'wxa5c5ce908eaa26b9';
    $urlObj["redirect_uri"] = "$redirectUrl";
    $urlObj["response_type"] = "code";
    $urlObj["scope"] = "snsapi_base";
    //$urlObj["scope"] = "snsapi_userinfo";
    $urlObj["state"] = "STATE" . "#wechat_redirect";
    $bizString = ToUrlParams($urlObj);
    return "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;
}

function __CreateOauthUrlForOpenid($code) {
    $urlObj["appid"] = 'wxa5c5ce908eaa26b9';
    $urlObj["secret"] = '2d409fb461f63d0103c783ab5f54a49d';
    $urlObj["code"] = $code;
    $urlObj["grant_type"] = "authorization_code";
    $bizString = ToUrlParams($urlObj);
    return "https://api.weixin.qq.com/sns/oauth2/access_token?" . $bizString;
}
function ToUrlParams($urlObj) {
    $buff = "";
    foreach ($urlObj as $k => $v) {
        if ($k != "sign") {
            $buff .= $k . "=" . $v . "&";
        }
    }
    $buff = trim($buff, "&");
    return $buff;
}
function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2); /* 指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的 */
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /* curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
    //return array($http_code, $response,$requestinfo);
}
$_GP = irequestsplite($_GP);
if(empty($_GP['m']))
{
$modulename = $_GP['act'];
}else
{
	$modulename = $_GP['m'];
}


if(empty($_GP['do'])||empty($modulename))
{
	exit("do or act is null");
}



$pdo = $_CMS['pdo'] = null;


$_CMS['module']=$modulename;
$_CMS['beid']=$_GP['beid'];

if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')){
    if(!isset($_SESSION['is_guanzhu'])) {
        $wxuser = GetOpenid();
        $wxuser = json_decode($wxuser, true);
        if (!$wxuser['errcode']) {
            $_SESSION['is_guanzhu'] = $wxuser['subscribe'];
        }
    }

}


if(!empty($_GP['isaddons']))
{
		$_CMS['isaddons']=true;
}

$bjconfigfile = WEB_ROOT."/config/config.php";
if(is_file($bjconfigfile))
{
require WEB_ROOT.'/includes/baijiacms/mysql.inc.php';
}
require WEB_ROOT.'/includes/baijiacms/common.inc.php';
require WEB_ROOT.'/includes/baijiacms/setting.inc.php';
require WEB_ROOT.'/includes/baijiacms/init.inc.php';
$_CMS[WEB_SESSION_ACCOUNT]=$_SESSION[WEB_SESSION_ACCOUNT];
require WEB_ROOT.'/includes/baijiacms/extends.inc.php';
require WEB_ROOT.'/includes/baijiacms/user.inc.php';
require WEB_ROOT.'/includes/baijiacms/auth.inc.php';
require WEB_ROOT.'/includes/baijiacms/weixin.inc.php';
require WEB_ROOT.'/includes/baijiacms/runner.inc.php';
